package cn.ug.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * 微信相关工具类
 */
public class WxUtil {
    private static Log log = LogFactory.getLog(WxUtil.class);
    /**
     * 接入微信是使用的token
     **/
    private static final String token = "yougao";

    /**
     * 商户唯一编号
     **/
    public static String APPID = "wxe769207187f12669";
    /**测试商户唯一编号**/
    //public static String APPID = "wxf696019ef27725c6";
    /**
     * 商户唯一密钥
     **/
    public static String APPSECRET = "355fa2505e0230b5417320a67a4d51b7";
    /**测试商户唯一密钥**/
    //public static String APPSECRET = "d1812c21cefe1a77e38261319ef1232d";
    /**
     *
     * 微信弱授权url
     **/
    private static final String WX_ACCREDIT_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

    /**
     * 通过授权code获取token
     **/
    private static final String ACCREDIT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";


    /**
     * 发送微信模板消息url
     **/
    public static final String SEND_WX_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

    /**
     * 获取token的url
     **/
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    //编码
    private static final String ENCODING = "UTF-8";

    /**
     * 微信接入验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);

        StringBuffer content = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        String temp = getSha1(content.toString());

        return temp.equals(signature);
    }


    /**
     * Sha1
     *
     * @param str
     * @return
     */
    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取微信授权地址
     *
     * @param wxAccreditCallBackUrl 微信授权回调地址
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String getAccreditUrl(String wxAccreditCallBackUrl) throws ParseException, IOException {
        String callBackUrlStr = java.net.URLEncoder.encode(wxAccreditCallBackUrl, ENCODING);
        return WX_ACCREDIT_URL.replace("APPID", APPID).replace("REDIRECT_URI", callBackUrlStr);
    }


    /**
     * 通过授权code来 获取Access_token
     *
     * @param code
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject getAccreditAccesstokenByCode(String code) {
        String url = ACCREDIT_ACCESS_TOKEN_URL.replace("APPID", APPID).replace("SECRET", APPSECRET).replace("CODE", code);
        JSONObject jsonObject = null;
        try {
            jsonObject = doGetStr(url, ENCODING);
            log.info("微信请求结果:"+ JSON.toJSONString(jsonObject));
            if (!StringUtils.isBlank(jsonObject.getString("access_token"))) {
                return jsonObject;
            }
        } catch (Exception e) {
            log.error("微信请求错误:"+ e.getMessage());
        }
        return null;
    }

    /**
     * 获取accessToken
     *
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String getAccessToken() {
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        JSONObject jsonObject = doGetStr(url, ENCODING);
        if (jsonObject != null) {
            return jsonObject.getString("access_token");
        }
        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject doGetStr(String url, String encoding) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, encoding);
                jsonObject = JSONObject.parseObject(result);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * POST2请求
     *
     * @param url
     * @param outStr
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject doPostStr(String url, String outStr) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpost = new HttpPost(url);
        JSONObject jsonObject = null;
        httpost.setEntity(new StringEntity(outStr, "UTF-8"));
        HttpResponse response;
        String result;
        try {
            response = client.execute(httpost);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }



    public static void main(String[] args) {
        String stra = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=wxe769207187f12669&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
        JSONObject jsonObject = doGetStr(stra,"utf-8");
        System.out.println(jsonObject.toJSONString());
    }
}
